import { Injectable, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { UploadedFile } from './upload.types';
import { MinioService } from './minio.service';

@Injectable()
export class UploadService {
  constructor(
    private configService: ConfigService,
    private minioService: MinioService,
  ) {}

  /**
   * 上传单个文件
   */
  async uploadFile(
    file: UploadedFile,
    type: 'tool' | 'avatar' | 'temp' = 'temp',
  ): Promise<{ url: string; filename: string }> {
    try {
      // 验证文件
      this.validateFile(file);

      // 上传到 MinIO，返回完整URL
      const url = await this.minioService.uploadFile(file, type);
      
      // 从URL中提取文件名
      const filename = url.split('/').pop() || '';

      return { url, filename };
    } catch (error) {
      throw new BadRequestException(`文件上传失败: ${error.message}`);
    }
  }

  /**
   * 批量上传文件
   */
  async uploadFiles(
    files: UploadedFile[],
    type: 'tool' | 'avatar' | 'temp' = 'temp',
  ): Promise<Array<{ url: string; filename: string }>> {
    const results = [];
    
    for (const file of files) {
      const result = await this.uploadFile(file, type);
      results.push(result);
    }

    return results;
  }

  /**
   * 删除文件
   */
  async deleteFile(url: string): Promise<boolean> {
    try {
      await this.minioService.deleteFile(url);
      return true;
    } catch (error) {
      return false;
    }
  }

  /**
   * 验证文件
   */
  private validateFile(file: UploadedFile) {
    const maxSize = 5 * 1024 * 1024; // 5MB
    const allowedMimes = [
      'image/jpeg',
      'image/jpg',
      'image/png',
      'image/gif',
      'image/webp',
      'image/svg+xml',
    ];

    if (!allowedMimes.includes(file.mimetype)) {
      throw new BadRequestException(
        '不支持的文件类型，仅支持: JPG, PNG, GIF, WebP, SVG',
      );
    }

    if (file.size > maxSize) {
      throw new BadRequestException('文件大小不能超过 5MB');
    }
  }

}


